﻿
package extremefx.crypto.hash {
	import flash.utils.ByteArray;	
		
	/**
	 * @author Marcelo Volmaro
	 */
	 
	public final class HMAC {
		private var hash:IHash;
		private var bits:uint;
		
		public function HMAC(pHash:IHash, pBits:uint=0) {
			hash = pHash;
			bits = pBits;
		}
		
		/**
		 * Compute a HMAC using a key and some data.
		 * It doesn't modify either, and returns a new ByteArray with the HMAC value.
		 */
		 
		public function compute(key:ByteArray, data:ByteArray):ByteArray {
			var hashKey:ByteArray;
			if (key.length>hash.getInputSize()) {
				hashKey = hash.hash(key);
				
			} else {
				hashKey = new ByteArray;
				hashKey.writeBytes(key);
			}
			
			while (hashKey.length<hash.getInputSize()) {
				hashKey[hashKey.length]=0;
			}
			
			var innerKey:ByteArray = new ByteArray;
			var outerKey:ByteArray = new ByteArray;
			
			for (var i:uint=0;i<hashKey.length;++i) {
				innerKey[i] = hashKey[i] ^ 0x36;
				outerKey[i] = hashKey[i] ^ 0x5c;
			}
			
			// inner + data
			innerKey.position = hashKey.length;
			innerKey.writeBytes(data);
			var innerHash:ByteArray = hash.hash(innerKey);
			// outer + innerHash
			outerKey.position = hashKey.length;
			outerKey.writeBytes(innerHash);
			var outerHash:ByteArray = hash.hash(outerKey);
			if (bits>0 && bits<8*outerHash.length) {
				outerHash.length = bits/8;
			}
			
			return outerHash;
		}
		
		public function dispose():void {
			hash = null;
			bits = 0;
		}
		
		public function toString():String {
			return "hmac-"+(bits>0?bits+"-":"")+hash.toString();
		}
	}
}
